# -*- coding: utf-8 -*-

from utils.operators.cluster_for_spark_sql_operator import SparkSqlOperator
from datetime import timedelta
from jms_hi.dwd.tab.dwd_tab_barscan_collect_base_hi import jms_dwd__dwd_tab_barscan_collect_base_hi
from jms_hi.dim.dim_network_whole_massage import jms_dim__dim_network_whole_massage
from airflow.exceptions import AirflowSkipException
import pendulum

cst = pendulum.timezone('Asia/Shanghai')

class HiSparksqlOperator(SparkSqlOperator):
    def pre_execute(self, context):
        day = cst.convert(context['ti'].execution_date) + timedelta(days=1)

        days_of_hours = ['07']

        if day.strftime('%H') not in days_of_hours:
            print(f'{day.strftime("%H")} not in {days_of_hours}, should skip')
            raise AirflowSkipException()
        else:
            print(f'{day.strftime("%H")} in {days_of_hours}, run now')
            super().pre_execute(context)


jms_hi_dm__dm_not_out_scan_8hour_detail_dt = HiSparksqlOperator(
    task_id='jms_hi_dm__dm_not_out_scan_8hour_detail_dt',
    task_concurrency=1,
    pool_slots=2,
    master='yarn',
    name='jms_hi_dm__dm_not_out_scan_8hour_detail_dt_{{ execution_date | hour_add(1) | cst_hour }}',
    sql='jms_hi/dm/dm_not_out_scan_8hour_detail_dt/execute.sql',
    driver_cores=2,
    driver_memory='4G',
    executor_cores=2,
    executor_memory='4G',
    num_executors=6,  # spark.dynamicAllocation.enabled 为 True 时，num_executors 表示最少 Executor 数
    conf={'spark.dynamicAllocation.enabled'                  : 'true',  # 动态资源开启
          'spark.shuffle.service.enabled'                    : 'true',  # 动态资源 Shuffle 服务开启
          'spark.dynamicAllocation.maxExecutors'             : 10,  # 动态资源最大扩容 Executor 数
          'spark.dynamicAllocation.cachedExecutorIdleTimeout': 120,  # 动态资源自动释放闲置 Executor 的超时时间(s)
          'spark.sql.sources.partitionOverwriteMode'         : 'dynamic',  # 允许删改已存在的分区
          'spark.executor.memoryOverhead'                    : '2G',  # 堆外内存
          'spark.sql.shuffle.partitions'                     : 60,
          'spark.default.paralleism'                         : 36, # num-executors * executor-cores的2~3倍较为合适
          },
    hiveconf={'hive.exec.dynamic.partition'             : 'true',  # 动态分区
              'hive.exec.dynamic.partition.mode'        : 'nonstrict',
              'hive.exec.max.dynamic.partitions'        : 20,  # 每天生成 20 个分区
              'hive.exec.max.dynamic.partitions.pernode': 20,  # 每天生成 20 个分区
              },
    execution_timeout=timedelta(minutes=30),
    email=['guoruiling@yl-scm.com', 'yl_bigdata@yl-scm.com'],
)

jms_hi_dm__dm_not_out_scan_8hour_detail_dt << [
    jms_dwd__dwd_tab_barscan_collect_base_hi, jms_dim__dim_network_whole_massage
]
